package org.bspv.pharma.manager.impl;

import java.util.List;

import org.bspv.pharma.dao.PlaceDAO;
import org.bspv.pharma.manager.PlaceManager;
import org.bspv.pharma.model.Place;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 
 * @author guillaume
 * 
 */
@Service(value = "placeManager")
public class PlaceManagerImpl extends AbstractManagerImpl<Place, Long> implements PlaceManager {

    /**
     * Constructeur.
     * 
     * @param dao
     */
    @Autowired
    public PlaceManagerImpl(PlaceDAO dao) {
        super(dao);
    }

    /**
     * {@inheritDoc}
     * @see org.bspv.pharma.manager.PlaceManager#findByCode(String)
     */
    public Place findByCode(String placeCode) {
        return dao.findUniqueResultBy("code", placeCode);
    }

    /**
     * {@inheritDoc}
     * @see org.bspv.pharma.manager.PlaceManager#findTopPlaces()
     */
    public List<Place> findTopPlaces() {
        String[] empty = {};
        String[] keys = { "level" };
        Object[] values = { 1 };
        String[] nullProperties = { "obsolete" };
        return dao.findBy(keys, values, nullProperties, empty);
    }

    /**
     * {@inheritDoc}
     * @see org.bspv.pharma.manager.PlaceManager#findValidChildren(Place)
     */
    public List<Place> findValidChildren(Place parent) {
        String[] empty = {};
        String[] keys = { "parent" };
        Object[] values = { parent };
        String[] nullProperties = { "obsolete" };
        return dao.findBy(keys, values, nullProperties, empty);
    }

    /**
     * {@inheritDoc}
     * @see org.bspv.pharma.manager.PlaceManager#findAllValidChildren(Place)
     */
    public List<Place> findAllValidChildren(Place parent) {
        return ((PlaceDAO) dao).findAllValidChildren(parent);
    }

    /**
     * {@inheritDoc}
     * @see org.bspv.pharma.manager.impl.AbstractManagerImpl#save(java.lang.Object)
     * Surcharge de la méthode pour appeler les méthodes update et add du dao.
     */
    @Override
    public Place save(Place element) {
        Place newPlace = null; 
        if (element.getId() == null || element.getId().equals(0L)) {
            // Nouvel emplacement
            Long id = ((PlaceDAO) dao).add(element);
            //Rechargement du nouvel emplacement
            newPlace = dao.findById(id);
        } else {
            // Mise à jour
            newPlace = ((PlaceDAO) dao).update(element);
        }
        return newPlace;
    }

    
}
